from django.shortcuts import render,redirect
import os
from django.conf import settings
import time
from difflib import HtmlDiff

"""
需求基本实现；目前存在的问题：
1、似乎有文件大小的限制
2、增加LOG日志功能
"""

def diff_comp(request,):

    #通过POST请求获取前端传递的数据
    if request.method == 'POST':
        #通过html name属性中的值获取数据

        file_obj1 = request.FILES.get('file1')
        lins1=[]
        for chunk in file_obj1.chunks():
            lins1 = chunk.decode('utf-8').splitlines()

        file_obj2 = request.FILES.get('file2')
        lins2 = []
        for chunk in file_obj2.chunks():
            lins2 = chunk.decode('utf-8').splitlines()


        html_diff = HtmlDiff()
        result = html_diff.make_file(lins1,lins2)

        #os.remove("/templates/diff_result.html")
        with open("/Users/yunhui.han/yunwei/ywpt/netdevops/templates/diff_result.html", "w", encoding="utf8") as f:
            f.write(result)

        return render(request, "diff_result.html")
    return render(request, "diff.html")
        #获取上传文件的名称
        #file_name1 = file_obj1.name
        # #定义存放目录
        # file_path1 = os.path.join(settings.STATIC_ROOT,file_obj1.name)
        # #写入数据
        # with open(file_path1,'wb+') as f:
        #     lins = []
        #     for chunk in file_obj1.chunks():
        #         lins = f.write(chunk)
        #         print(lins)
        #
        # file_obj2 = request.FILES.get('file2')
        # file_name2 = file_obj2.name
        # file_path2 = os.path.join(settings.STATIC_ROOT, file_obj2.name)
        # with open(file_path2,'wb+') as f:
        #     lins = []
        #     for chunk in file_obj2.chunks():
        #         f.write(chunk)
        #         print(lins)
        # time.sleep(3)
        # #以下实现文本对比
        # def get_file_content(file_path):
        #     lines = []
        #     with open(file_path, mode="r", encoding="utf8") as f:
        #         lines = f.read().splitlines()
        #     return lines
        #
        # def compare_file(file1, file2):
        #     lines1 = get_file_content(file1)
        #     lines2 = get_file_content(file2)
        #
        #     # 找出差异输出到result(str)
        #     html_diff = HtmlDiff()
        #     result = html_diff.make_file(lines1, lines2)
        #
        #     # 将差异写入html文件
        #     with open("/Users/yunhui.han/yunwei/ywpt/netdevops/templates/diff_result.html", "w", encoding="utf8") as f:
        #         f.write(result)
        #
        # compare_file(f'/Users/yunhui.han/yunwei/ywpt/netdevops/media/{file_name1}',f'/Users/yunhui.han/yunwei/ywpt/netdevops/media/{file_name2}')
    #     return render(request, "diff_result.html")
    # return render(request,"diff.html")
